package com.dingwen.treasure.influxdb.config;

import com.influxdb.client.*;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 时序数据库配置
 *
 * @author dingwen
 * @date 2023/01/09
 */
@Configuration(proxyBeanMethods = true)
@ConfigurationProperties(prefix = "influxdb")
@Getter
@Setter
public class InfluxdbConfig {

    /**
     * influxdb数据库地址
     */
    private String url = "http://192.168.2.215:8037";
    /**
     * 组织名称
     */
    private String org = "dw";

    /**
     * 令牌
     */
    private String token = "h4OFrk8oOU5R5iKGQgOpb4niUc80139OgREB2BGAgKT1J39Wn0-T0aXzmWld27BpVR74ggoNF5D-A==";


    /**
     * 异步写入批量处理大小
     */
    private Integer asyncWriteBatchSize = 100;


    /**
     * 异步写入批量处理时间间隔
     */
    private Integer asyncFlushInterval = 1000;


    /**
     * 时序数据库客户端
     *
     * @return {@link InfluxDBClient}
     */
    @Bean
    public InfluxDBClient influxDBClient() {
        return InfluxDBClientFactory.create(
                url,
                token.toCharArray(),
                org
        );
    }

    /**
     * 同步写
     *
     * @return 同步写api
     */
    @Bean
    public WriteApiBlocking writeApiBlocking() {
        return influxDBClient().getWriteApiBlocking();
    }


    /**
     * 异步写
     *
     * @return {@link WriteApi}
     */
    @Bean
    public WriteApi writeApi() {
        // 默认10s内达到100条刷库
        WriteOptions options = WriteOptions.builder()
                .batchSize(asyncWriteBatchSize)
                .flushInterval(asyncFlushInterval)
                .build();
        return influxDBClient().makeWriteApi(options);
    }

    /**
     * 查询api
     *
     * @return {@link QueryApi}
     */
    @Bean
    public QueryApi queryApi() {
        return influxDBClient().getQueryApi();
    }
}
